import os
import platform
import sys
import time
import serial

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from tools import get_yaml
from log_info import logger


class Rotor:
    def __init__(self, get_ser=None):
        self.ser = None
        self.cfg = get_yaml("rotor/base/rotor.yml")
        if get_ser is not None:
            self.get_server(get_ser)

    def get_server(self, car):
        self.ser = car.base_moto.ser
        self.ser.do = self.ser.get_answer

    def do_task(self, task, wait=0.7):
        if self.ser is not None:
            task_command = self.cfg[task]
            command_bytes = bytes.fromhex(task_command)
            self.ser.do(command_bytes)
            time.sleep(wait)
        else:
            logger.info("rotor还没有获取服务")


class rotor_test(Rotor):
    def __init__(self):
        super(Rotor, self).__init__()
        if "Windows" in platform.platform():
            self.ser = serial.Serial('COM8', 1000000)
        else:
            self.ser = serial.Serial('/dev/ttyUSB0', 1000000)
        self.ser.do = self.ser.write
        self.cfg = get_yaml("rotor/base/rotor.yml")


if __name__ == "__main__":
    rotor = rotor_test()
    rotor.do_task("start", wait=5)
